package com.mh.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

//自定义退出处理器
//自定义的 LogoutSuccessHandler 实现类,用于处理用退出后的逻辑
@Component
public class MyLogoutHandlerImpl implements LogoutSuccessHandler {
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        //在用户退出后, 返回一个 JSON 响应
        HashMap<String, Object> map = new HashMap<>();
        map.put("msg","退出成功");
        map.put("code",200);

        //设置前端响应JSON编码格式
        response.setContentType("application/json;charset=utf-8");
        //使用 ObjectMapper 将 HashMap 转换为 JSON 字符串
        String s = new ObjectMapper().writeValueAsString(map);
        //将JSON响应返回给客户端
        response.getWriter().print(s);
    }
}
